﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace Handrise.CDCable.Mobile.Business
{
    /// <summary>
    /// 计划设备服务
    /// </summary>
    public class PlanDeviceService
    {
        public event ScanCompleteHandler OnScanComplete;

        /// <summary>
        /// 删除对应计划下的所有设备
        /// </summary>
        /// <param name="planID"></param>
        /// <returns></returns>
        public bool DeletePlanDeviceByPlan(string planID)
        {
            return AppLogic.dataService.Delete<PlanDevice>("PlanID ='" + planID + "'", null) > 0;
        }

        /// <summary>
        /// 处理新接收到的计划设备 
        /// </summary>
        /// <param name="planDevices"></param>
        public void DealNewReceivedPlanDevice(List<object> planDevices)
        {
            DeviceService deviceService = new DeviceService();
            DeviceGPSService deviceGPSService = new DeviceGPSService() ;
            foreach (PlanDevice planDevice in planDevices)
            {
                //处理计划设备数据
                planDevice.UserName = AppLogic.LoginUser.UserName;

                //设置设备信息
                Device device = deviceService.GetDeviceByCode(planDevice.DeviceCode);
                if (device != null)
                {
                    planDevice.DeviceID = device.DeviceID;
                    planDevice.DeviceName = device.Name;
                    planDevice.DeviceType = device.DeviceType;
                }

                //设置经纬度
                DeviceGPS deviceGPS = deviceGPSService.GetDeviceGPSByDeviceCode(planDevice.DeviceCode);
                if (deviceGPS != null)
                {
                    try
                    {
                        string[] gpsInfo = deviceGPS.GPSInfo.Split('|')[0].Split(';')[0].Split(',');
                        planDevice.Longitude = double.Parse(gpsInfo[0]);
                        planDevice.Latitude = double.Parse(gpsInfo[1]);
                    }
                    catch (Exception)
                    {
                    }

                }

                //新计划设备
                AppLogic.dataService.Add<PlanDevice>(planDevice);

            }
        }

        /// <summary>
        /// 获取当前经纬度范围之内的所有巡视设备
        /// </summary>
        /// <param name="planID">计划ID</param>
        /// <param name="longitude">返回当前的经度</param>
        /// <param name="latitude">返回当前的纬度</param>
        /// <returns>所有在改范围内的巡视设备</returns>
        public List<PlanDevice> GetPlanDeviceInGPSRange(string planID, out double longitude, out double latitude)
        {
            List<PlanDevice> reList = new List<PlanDevice>();

            //先获取当前经纬度
            if (!AppLogic.gpsTraceService.GetGPSInfo(out longitude, out latitude))
                return reList;

            //获取所有该计划的巡视设备
            List<PlanDevice> planDevices = AppLogic.dataService.Find<PlanDevice>("PlanID ='" + planID + "'", "");
            
            //获取配置的确认距离
            double distance = 10;
            try
            {
                distance = double.Parse(AppLogic.config.GetParameter("Configuration/GPSComfire", "Distance"));
            }
            catch 
            {
            }

            //计算小于设置确认距离内的巡视设备
            foreach (PlanDevice  planDevice in planDevices)
            {
                if(planDevice.Longitude.HasValue && planDevice.Latitude.HasValue)
                {
                    double currentDistance = AppLogic.gpsTraceService.DistanceOfTwoPoints(planDevice.Longitude.Value,planDevice.Latitude.Value,longitude,latitude);
                    if (currentDistance > 0 && currentDistance <= distance)
                    {
                        reList.Add(planDevice);
                    }
                }
            }

            return reList;
        }

        /// <summary>
        /// 设备确认到位
        /// </summary>
        /// <param name="planDevices">多个巡视设备</param>
        /// <param name="confirmType">确认类型：GPSConfirm、ScanConfirm</param>
        public void PlanDeviceConfirmLocation(List<PlanDevice> planDevices,string confirmType,double longitude,double latitude)
        {
            foreach (PlanDevice planDevice in planDevices)
            {
                if (planDevice.ConfirmState == "已确认")
                    continue ;

                planDevice.ConfirmState = "已确认";
                AppLogic.dataService.Update<PlanDevice>(planDevice);

                //把确认点设置到轨迹中
                GPSTrace gpsTrace = new GPSTrace();
                gpsTrace.GPSTraceID = Guid.NewGuid().ToString();
                gpsTrace.CollectType = confirmType;
                gpsTrace.CollectDateTime = DateTime.Now;
                if (confirmType == "ScanConfirm")
                {
                    gpsTrace.Latitude = planDevice.Latitude;
                    gpsTrace.Longitude = planDevice.Longitude;
                }
                else
                {
                    gpsTrace.Latitude = latitude;
                    gpsTrace.Longitude = longitude;
                }
                //从设备类型中获取设备位置
                EquipmentTypeService equipmentTypeService = new EquipmentTypeService();
                gpsTrace.DeviceLocate = equipmentTypeService.GetDeviceLocate(planDevice.DeviceType);
                gpsTrace.ReportState = "未上报";
                gpsTrace.UserName = AppLogic.LoginUser.UserName;
                gpsTrace.DeviceCode = planDevice.DeviceCode;
                AppLogic.gpsTraceService.InsertComfireGPS(gpsTrace);
            }
        }

        ///// <summary>
        ///// 设备确认到位
        ///// </summary>
        ///// <param name="planDevice">到位的设备</param>
        ///// <param name="isGPS">是否是GPS确认</param>
        ///// <param name="isScan">是否是扫描确认</param>
        //public void PlanDeviceComfireLocation(PlanDevice planDevice,bool isGPS,bool isScan)
        //{
        //    if (planDevice.ConfirmState == "已确认")
        //        return;

        //    planDevice.ConfirmState = "已确认";
        //    AppLogic.dataService.Update<PlanDevice>(planDevice);

        //    if (isGPS)
        //    {
        //        GPSTrace gpsTrace = new GPSTrace();
        //        gpsTrace.GPSTraceID = Guid.NewGuid().ToString();
        //        gpsTrace.CollectType = "GPSConfirm";
        //        gpsTrace.CollectDateTime = DateTime.Now;
        //        gpsTrace.Latitude = planDevice.Latitude;
        //        gpsTrace.Longitude = planDevice.Longitude;
        //        gpsTrace.ReportState = "未上报";
        //        gpsTrace.UserName = AppLogic.LoginUser.UserName;
        //        AppLogic.gpsTraceService.InsertComfireGPS(gpsTrace);
        //    }

        //    if (isScan)
        //    {
        //        GPSTrace gpsTrace = new GPSTrace();
        //        gpsTrace.GPSTraceID = Guid.NewGuid().ToString();
        //        gpsTrace.CollectType = "ScanConfirm";
        //        gpsTrace.CollectDateTime = DateTime.Now;
        //        gpsTrace.Latitude = planDevice.Latitude;
        //        gpsTrace.Longitude = planDevice.Longitude;
        //        gpsTrace.ReportState = "未上报";
        //        gpsTrace.UserName = AppLogic.LoginUser.UserName;
        //        AppLogic.gpsTraceService.InsertComfireGPS(gpsTrace);
        //    }


        //}

        ///// <summary>
        ///// 通过条码获取巡视设备
        ///// </summary>
        ///// <returns></returns>
        //public PlanDevice GetPlanDeviceIDByCode(string deviceCode)
        //{
        //    return AppLogic.dataService.GetFirstEntity<PlanDevice>("DeviceCode = '" + deviceCode + "'", "");
        //}

        /// <summary>
        /// 通过条码获取对应巡视计划中的巡视设备
        /// </summary>
        /// <param name="planID"></param>
        /// <param name="deviceCode"></param>
        /// <returns></returns>
        public PlanDevice GetPlanDeviceByCode(string planID, string deviceCode)
        {
            return AppLogic.dataService.GetFirstEntity<PlanDevice>("DeviceCode = '" + deviceCode + "' and PlanID = '" + planID + "'", "");
        }

        /// <summary>
        /// 获取巡视设备
        /// </summary>
        /// <param name="PlanID"></param>
        /// <param name="deviceCode"></param>
        /// <param name="deviceName"></param>
        /// <param name="deviceType"></param>
        /// <returns></returns>
        public List<PlanDevice> GetPlanDevice(string planID, string deviceCode, string deviceName, string deviceType)
        {
            string filter = "(PlanID = '" + planID + "')";
            if (deviceCode != "")
                filter += "and (DeviceCode = '" + deviceCode + "') ";
            if (deviceName != "")
                filter += "and (DeviceName like '%" + deviceName + "%') ";
            if (deviceType != "")
                filter += "and (DeviceType = '" + deviceType + "') ";

            return AppLogic.dataService.Find<PlanDevice>(filter, "");
        }


        /// <summary>
        /// 通过sql获取巡视设备
        /// </summary>
        /// <param name="PlanID"></param>
         /// <param name="wheresql">sql条件</param>
        /// <returns></returns>
        public List<VPlanDevice> GetsqlPlanDevice( string wheresql)
        {
              return AppLogic.dataService.Find<VPlanDevice>(wheresql, "");
        }


        /// <summary>
        /// 获取已巡视过的设备
        /// </summary>
        /// <param name="planID"></param>
        /// <param name="deviceCode"></param>
        /// <param name="deviceName"></param>
        /// <param name="deviceType"></param>
        /// <returns></returns>
        public List<PlanDevice> GetAlreadyPatrolPlanDevice(string planID, string deviceCode, string deviceName, string deviceType)
        {
            string filter = "(PlanID = '" + planID + "') and (ConfirmState = '已确认') ";
            if (deviceCode != "")
                filter += "and (DeviceCode = '" + deviceCode + "') ";
            if (deviceName != "")
                filter += "and (DeviceName like '%" + deviceName + "%') ";
            if (deviceType != "")
                filter += "and (DeviceType = '" + deviceType + "') ";

            return AppLogic.dataService.Find<PlanDevice>(filter, "");
        }
        

    }

    public delegate void ScanCompleteHandler(string code);
}
